import { memo, useEffect } from "react"
import type { FeeInfo, Station } from "../services"
import { FeeType, modifyFeeInfo } from "../services"
import { Button, Form, InputNumber, Modal, Select, TimePicker } from "antd"
import { styled } from '@umijs/max'
import { enum2options } from "@/utils/enum2options"
import dayjs from "dayjs"
import { MinusCircleOutlined, PlusCircleOutlined } from "@ant-design/icons"
import { Access } from "@umijs/max"
import { useRequest } from "ahooks"
import { dayjs2minutes, minutes2dayjs } from "@/utils/common"

const FeeContainer = styled.div`
  width: 100%;
  display: grid;
  // grid-template-columns: 1fr 1fr 1fr 2fr 2fr 36px;
  grid-template-columns: 1fr 1fr 2fr 2fr 36px;
  gap: 16px;

  .require {
    display: flex;
    align-items: center;
    gap: 8px;

    .label {
      width: max-content;
      flex-shrink: 0;
    }

    .ant-input-number {
      flex: 1;
    }
   
    .label::before {
      content: '*';
      color: red;
    }

    .label::after {
      content: ':';
    }
  }

  .operation {
    display: flex;
    align-items: center;
    gap: 8px;
  }
`

/** 最晚结束时间 23:59 -> 1439 */
const LastEndTime = 1439
const Hours: number[] = new Array(24).fill(0).map((_,i) => i)
const Minutes: number[] = new Array(60).fill(0).map((_,i) => i)

interface FeeItemProps {
  value?: FeeInfo
  onChange?: (value: Partial<FeeInfo>) => void
  add: (value?: Partial<FeeInfo>, index?: number) => void
  remove: (index: number) => void
  index: number
  isLast: boolean
  nextEndTime: number
  setNextEndTime: (index: number, endTime: number) => void
}

const getDisabledTime = (min: number, max: number) => {
  const minHour = Math.floor(min / 60)
  const minMinute = min % 60
  const maxHour = Math.floor(max / 60)
  const maxMinute = max % 60
  return {
    disabledHours: () => Hours.filter(it => it < minHour || it > maxHour),
    disabledMinutes: (h: number) => {
      if (h === minHour) {
        return Minutes.filter(it => it < minMinute)
      } else if (h === maxHour) {
        return Minutes.filter(it => it > maxMinute)
      } else if (h > maxHour || h < minHour) {
        return Minutes
      }
      return []
    }
  }
}

const FeeItem: React.FC<FeeItemProps> = props => {
  const data = props.value

  const add = () => {
    if (data?.endTime === LastEndTime) {
      Modal.warning({
        title: '提示',
        content: '已无剩余时间可添加'
      })
      return
    }
    props.add({type: FeeType.平时, startTime: data!.endTime! + 1, endTime: LastEndTime})
  }

  const setData = (d: FeeInfo) => {
    props.onChange?.(d)
  }

  const onEndTimeChange = (val: dayjs.Dayjs) => {
    const endTime = dayjs2minutes(val)
    new Promise((resolve) => {
      props.setNextEndTime(props.index, endTime)
      resolve(true)
    })
  }

  return (
    <FeeContainer>
      {/* <Select value={data?.type} options={enum2options(FeeType)} disabled onChange={val => setData({...data!, type: val})} /> */}
      <TimePicker format='HH:mm' value={minutes2dayjs(data?.startTime)} disabled />
      <TimePicker
        format='HH:mm' value={minutes2dayjs(data?.endTime)} allowClear={false}
        onChange={val => onEndTimeChange(val!)}
        disabled
        disabledTime={() => getDisabledTime((data?.startTime || 0) + 1, props.isLast ? LastEndTime : props.nextEndTime - 2)}
      />
      <div className="require">
        <span className="label">基础电费（元）</span>
        <InputNumber
          placeholder="请输入" min={0}
          disabled
          className='electricFee' value={data?.electricFee}
          onChange={val => setData({...data!, electricFee: val || 0})}
        />
      </div>
      <div className="require">
        <span className="label">服务费（元）</span>
        <InputNumber
          placeholder="请输入" min={0}
          disabled
          className='serviceFee' value={data?.serviceFee}
          onChange={val => setData({...data!, serviceFee: val || 0})}
        />
      </div>
      <div className="operation">
        <Access accessible={props.isLast && false}>
          <PlusCircleOutlined style={{color: 'green', cursor: 'pointer'}} onClick={add} />
        </Access>
        <Access accessible={props.isLast && props.index > 0 && false}>
          <MinusCircleOutlined style={{color: 'red', cursor: 'pointer'}} onClick={() => props.remove(props.index)} />
        </Access>
      </div>
    </FeeContainer>
  )
}

export interface FeeModalProps {
  open?: boolean
  station?: Station
  editable?: boolean
  onCancel?: (refresh?: boolean) => void
}

const FeeModal: React.FC<FeeModalProps> = props => {
  const [feeForm] = Form.useForm()
  const feeList = Form.useWatch('feeList', feeForm)
  const modifyReq = useRequest(modifyFeeInfo, {manual: true})

  const onCancel = (refresh?: boolean) => {
    props.onCancel?.(refresh)
  }

  const setNextEndTime = (index: number, endTime: number) => {
    feeForm.setFieldsValue({
      feeList: feeList.map((it: FeeInfo, idx: number) => {
        if (idx === index) {
          return {...it, endTime}
        } else if (idx === index + 1) {
          return {...it, startTime: endTime + 1}
        }
        return it
      })
    })
  }

  const onOk = () => {
    if (feeList.some((item: FeeInfo) => !item.serviceFee || !item.electricFee)) {
      Modal.warn({
        title: '提醒',
        content: '存在为空的基础电费或服务费，请填写完整',
      })
      return
    }
    if (feeList.at(-1).endTime < LastEndTime) {
      Modal.warn({
        title: '提醒',
        content: '尚有剩余时间未分配',
      })
      return
    }
    const _feeList = feeList.map((item: FeeInfo) => {
      return [
        (Math.floor(item.endTime / 60) * 100) + (item.endTime % 60),
        item.electricFee,
        item.serviceFee,
        item.type
      ]
    })
    modifyReq.runAsync({
      id: props.station!.id,
      feeInfo: JSON.stringify(_feeList)
    }).then(() => {
      onCancel(true)
    })
  }

  useEffect(() => {
    if (props.station) {
      const _feeList = JSON.parse(props.station.feeInfo || '[]')
      // const _feeList = JSON.parse('[[2359, 1, 0.5, 1]]')
      if (_feeList.length) {
        let startTime = 0
        feeForm.setFieldsValue({
          // [700,0.1000,0.5000,1] -> [结束时间，服务费，电费，类型]
          // [700,0.1000,0.5000,1] -> [结束时间，电费，服务费，类型] 2024.07.06 改
          feeList: _feeList.map((item: any[]) => {
            const _startTime = startTime
            const endTime = (Math.floor(item[0] / 100) * 60) + (item[0] % 100)
            startTime = endTime + 1
            return {
              type: item[3],
              startTime: _startTime,
              endTime,
              electricFee: item[1],
              serviceFee: item[2],
            }
          })
        })
      } else {
        feeForm.setFieldsValue({
          feeList: [{type: FeeType.平时, startTime: 0, endTime: LastEndTime, electricFee: 0, serviceFee: 0}]
        })
      }
    }
  }, [props.station])

  return (
    <Modal
      title='电价设置'
      width={900}
      open={props.open}
      onCancel={() => onCancel()}
      onOk={onOk}
      confirmLoading={modifyReq.loading}
      footer={[
        <Button key='close' onClick={() => onCancel()}>关闭</Button>
      ]}
    >
      <span style={{whiteSpace: 'pre-line'}}>
        {
          `
            说明：
            1、针对峰尖谷平时间您可以自行调整，第一个结束时间调整后，第二个开始时间自动调整，依此类推，从上往下进行修改。
            2、默认四个峰尖谷平，您可以点击“添加计费区间”设置更加细致的计费时段。
          `
        }
      </span>
      <Form form={feeForm} style={{marginTop: 24}}>
        <Form.List name='feeList'>
          {(fields, { add, remove }) => {
            return fields.map((field, index) => (
              <Form.Item {...field} key={field.key}>
                <FeeItem
                  add={add} remove={remove} index={index} isLast={index === fields.length - 1} 
                  nextEndTime={feeList?.[index + 1]?.endTime || LastEndTime} 
                  setNextEndTime={setNextEndTime}
                />
              </Form.Item>
            ))
          }}
        </Form.List>
      </Form>
    </Modal>
  )
}

export default memo(FeeModal)